var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
var wxFailAuth = true;
var chongdianxiang_id = '';

Page({

  /**
     * 页面的初始数据
     */
  data: {
    tc: 0,
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',
    colorSet: '',

    uid: '',
    token: '',
    openid: 0,
    userinfo: {},

    noPower: false,
    cdx_info: '',
    canBorrow: '',

    images_url: 'http://img.maxdoge.com/2017/1230/17/5a4757f9a6596.jpg',
    has_cdb: false,

    userTime: '',

    yj_orderNo: '',
    ya_totalFee: 0,

    noticeStr: '暂无可用充电宝',

    arrayList: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
    powerList: [],
    remainNum:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    chongdianxiang_id = '';
    
    var tc = app.get_tc();
    var that = this;

    var titlename = tc == 1 ? '我的充電寶' : '我的充电宝';
    wx.setNavigationBarTitle({
      title: titlename,
    }); 
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('chongdianbao/chongdianbao',function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        tc: tc
      });
    });

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
    });

    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x
        })
      }
    })

    chongdianxiang_id = options.boxid ? options.boxid : '';
    this.reGetUserInfo();

  },

  reGetUserInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      wxFailAuth = res == -1;
      if (!wxFailAuth) {
        console.log("登录者信息：", res);
        that.setData({
          userinfo: res,
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid,
        });
   
        // that.get_cdb_info();
        
        that.getUseingCDB();
      }
    }, "");
  },

  //获取是否已持有充电宝
  getUseingCDB: function(){
    var that = this;
    console.log("是否持有充电宝： ");
    var privatekey = utilMd5.hexMD5(that.data.uid + 'isusingcdb' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "isusingcdb",
        uid: that.data.uid,
        privatekey: privatekey
      },
      success: function (responseData) {
        console.log("是否持有充电宝： ", responseData);
        var has_cdb = false;
        var time = '1分钟'
        var img_url = 'http://img.maxdoge.com/2017/1230/17/5a4757f9a6596.jpg';
        if(responseData.data.boxid){
          img_url = 'http://img.maxdoge.com/2017/1230/21/5a4792f70477f.jpg';
          has_cdb = true;
          var sTime = parseInt(responseData.data.stime);
          var timestamp = Date.parse(new Date());
          timestamp = timestamp / 1000;
          var user_time = timestamp - sTime;
          var hour = parseInt((user_time / 60) / 60);
          var minute = parseInt((user_time / 60) % 60) + 1;
          if(hour>=100){
            that.get_cdb_info();
          }else{
            if(hour > 0){
              time = hour+ '小时' + minute +'分';
            } else if (minute > 0) {
              time = minute + '分钟';
            }
            
            wx.hideLoading();
            // that.get_cdb_info();
            that.setData({
              images_url: img_url,
              has_cdb: has_cdb,
              userTime: time
            });
          }
          
        } else {
          that.get_cdb_info();
        }

      }
    });
  },

  //获取所有充电宝借用人信息
  getAllUseingCDB: function(){
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'allusingcdb' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "allusingcdb",
        uid: that.data.uid,
        privatekey: privatekey,
        binduid:util.orgid
      },
      success: function (responseData) {
        console.log("所有持有充电宝的人信息： ", responseData);
        var result = responseData.data;
        

         var arrayList = that.data.arrayList;
          for (var i = 0; i < arrayList.length; i++) {
            for (var j = 0; j < result.length; j++) {
              if (arrayList[i] == result[j].solt) {
                result[j].stime = that.toDate(result[j].stime);
                arrayList.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                // arrayList.push(powerList[j]);
                arrayList.splice(i, 0, result[j]);
              }
            }
          }

          console.log("powerList====", arrayList);
          that.setData({
              powerList: arrayList,
          })
         wx.hideLoading();
      }
    });
  },

   //时间戳转换时间  
  toDate:function(number){  
      var n=number * 1000;  
      var date = new Date(n);  
      var Y = date.getFullYear() + '-';  
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';  
      var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();  
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      return (Y+M+D+" "+h+m+s); 
  },



  set_YaJinInfo: function(order_no, total_fee){
    console.log("交押金结果：order_no = " + order_no + "; total_fee = " + total_fee);
    this.setData({
      yj_orderNo: order_no,
      ya_totalFee: total_fee
    })
    this.borrow_request(this.data.canBorrow);
  },

  //获取充电宝信息
  get_cdb_info: function(e){
    if (!chongdianxiang_id){
      chongdianxiang_id = 'RL1A031712000003';//李铭晟测试充电箱
    }
    var that = this;
    if (chongdianxiang_id) {
      //获取充电箱信息
      util.api({
        method: "GET",
        data: {
          ac: "cdblist",
          boxid: chongdianxiang_id
        },
        success: function (responseData) {
          console.log("充电箱信息：", responseData);
          var resData = responseData.data;
          // errCode:"IB000008"
          // errMsg:"智能柜响应超时"
          if (resData.errCode == "000000"){
            if (responseData.data.result && responseData.data.result.powerBankIdList.length > 0) {
              var powerList = responseData.data.result.powerBankIdList;
              var remainNum = responseData.data.result.remainNum;
              console.log("充电宝列表：", powerList);
              var canBrr = '';
              powerList.forEach(function (m, i) {
                var level = parseInt(m.level);
                canBrr = m;
                // if (level >= 3) {
                //   canBrr = m;
                // }else{
                //   canBrr = false;
                //   that.setData({
                //     noticeStr: '电量不足,请稍候再试!'
                //   })
                // }
              });

              var arrayList = that.data.arrayList;
              for (var i = 0; i < arrayList.length; i++) {
                for (var j = 0; j < powerList.length; j++) {
                  if (arrayList[i] == powerList[j].slot) {
                    arrayList.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                    // arrayList.push(powerList[j]);
                    arrayList.splice(i, 0, powerList[j]);
                  }
                }
              }

              console.log("arrayList", arrayList);
              that.getAllUseingCDB();
              that.setData({
                arrayList:arrayList,
                canBorrow: canBrr,
                noPower: canBrr ? false : true,
                remainNum : remainNum
              })
            }
          } else {
            that.setData({
              canBorrow: false,
              noPower: true,
              noticeStr: resData.errMsg
            })
          }
          wx.hideLoading();
        }
      });
    } else {
      wx.hideLoading();
      that.setData({
        noPower: true
      })
    }
  },

  //借充电宝
  borrow_action: function (e) {
    var that=this;
    var boxInfo = e.currentTarget.dataset.cdb;
    console.log(boxInfo);
    this.borrow_request(boxInfo);
  },

  borrow_request: function(boxInfo){
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    // if (this.data.yj_orderNo && this.data.ya_totalFee >= 2) {
      if(true){
      wx.showLoading({
        title: 'loading。。。',
      });
      var that = this;
      console.log("登录者信息： " + that.data.uid + ", token = " + that.data.token);
      var privatekey = utilMd5.hexMD5(that.data.uid + 'borrowcdb' + that.data.token);
      var pw_id = boxInfo.powerBankId;
      util.api({
        method: "POST",
        data: {
          ac: "borrowcdb",
          boxid: chongdianxiang_id,
          solt: boxInfo.slot,
          powerid: pw_id,
          uid: that.data.uid,
          orderid: that.data.yj_orderNo,
          privatekey: privatekey
        },
        success: function (responseData) {
          console.log("借充电宝返回： ", responseData);
          if (responseData.data.errCode == '000000') {
            that.getUseingCDB();
          } else {
            wx.showToast({
              title: responseData.data.errMsg,
            })
          }
          wx.hideLoading();
        }
      });
    } else {
      var path = "/pages/chongzhi/chongzhi?coin=2&disabled=true";
      wx.navigateTo({
        url: path,
      })
    }
  },


  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.navigateTo({ url: url })
    }
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },
  

  shareToPengyouquan: function (e) {
    if (wxFailAuth) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    app.saveFormId(e.detail.formId);//保存fromId

    var that = this;
    var shareImgUrl = util.api_host + "/wxxcxcode.php?haibao=1&uid=" + that.data.uid +
      "&shareuid=" + that.data.uid + "&hongbaoid=" + that.data.hongbaoId + "&inviteuid=" + that.data.uid;
    
    // this.showEWM(shareImgUrl);
    shareImgUrl = base64.encode(shareImgUrl);
    var url = "/pages/haibao-page/haibao-page?imgUrl=" + shareImgUrl;
    wx.navigateTo({ url: url })
  },

  //页面分享
  onShareAppMessage: function () {
    console.log("onShareAppMessage");
    var that = this;
    var invUid = this.data.uid ? this.data.uid : this.data.shareuid;
    return {
      title: "独乐乐不如众乐乐，有红包抢，必须通知好友",
      path: '/pages/hongbao/hongbao?hongbaoid=' + that.data.hongbaoId + '&shareuid=' + invUid + '&inviteuid=' + invUid
    };
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },

  showEWM: function (url) {
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },

})